﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;

namespace Radiation.Common
{
    public class ReverseDnsWorker
    {
        private Thread m_worker;
        public event EventHandler<GenericEventArgs> DomainFound;
        private string m_ip;
        private bool m_working = false;

        public ReverseDnsWorker()
        {
            m_worker = new Thread(threadFunction);
        }

        public void SearchDomain(string ip)
        {
            if (!m_working)
            {
                m_working = true;
                m_ip = ip;
                m_worker.Start();
            }
        }

        private void threadFunction()
        {
            try
            {
                IPHostEntry entry = Dns.GetHostEntry(m_ip);
                OnDomainFound(entry.HostName);
            }
            catch (Exception)
            {
                Logger.Instance["error"].add("ReverseDnsWorker : Unable to resolve IP " + m_ip);
            }

            m_working = false;
        }

        protected virtual void OnDomainFound(string domain)
        {
            GenericEventArgs args = new GenericEventArgs();
            args["message"] = domain;
            if (DomainFound != null)
                DomainFound(this, args);
        }
    }
}
